﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BossCtrl : MonoBehaviour {

	public float _speed;

	private GameObject m_Player = null;

	private Animator m_anmi = null;

	public float m_health = 100;

	private float m_timer;

	bool isDie = false;

	// Use this for initialization
	void Start () {
		m_Player = GameObject.FindGameObjectWithTag ("Player");
		m_anmi = GetComponent<Animator> ();
	}

	public void GetHurt(float hp) {

		if (isDie) {
			return;
		}

		m_health -= hp;

		GetComponent<SpriteRenderer> ().color = Color.red;

		if (m_health <= 0) {
			isDie = true;
			m_anmi.SetTrigger ("Die");

			Destroy (gameObject, 1);
		}
	}

	void Move() {
		if (null == m_Player) {
			return;
		}

		m_anmi.SetBool ("Run", false);
		m_anmi.SetBool ("Attack", false);

		if (Vector3.Distance(transform.position, m_Player.transform.position) <= 4
			&& Vector3.Distance(transform.position, m_Player.transform.position) >= 1.5) {

			m_anmi.SetBool ("Run", true);

			transform.position += (m_Player.transform.position - transform.position).normalized * Time.deltaTime * _speed;

			if (m_Player.transform.position.x < transform.position.x) {
				transform.rotation = Quaternion.Euler (0, 0, 0);
			}

			if (m_Player.transform.position.x > transform.position.x) {
				transform.rotation = Quaternion.Euler (0, 180, 0);
			}
		}

		if (Vector3.Distance(transform.position, m_Player.transform.position) <= 1.5) {
			m_anmi.SetBool ("Attack", true);
		}
	}
	
	// Update is called once per frame
	void Update () {
		if (!isDie) {
			Move ();
		}

		if (GetComponent<SpriteRenderer>().color == Color.red) {
			m_timer += Time.deltaTime;

			if (m_timer > 0.3f) {
				GetComponent<SpriteRenderer> ().color = Color.white;
				m_timer = 0;
			}
		}
	}
}
